//
//  ZYCProtalNoticeView.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/21.
//

#import "ZYCProtalNoticeView.h"
#import "LxGridViewFlowLayout.h"
#import "TZTestCell.h"
#import "ZYCNoticePushView.h"

#define MAX_STARWORDS_LENGTH 40
#define BTImageTotalNumber 9
#define ZYCContentPlaceholder @"请输入通知内容..."
#define ZYCContentPlaceholderColor [UIColor colorWithHexString:@"#C3C3C3" alpha:1.0]

@interface ZYCProtalNoticeView ()<UITextFieldDelegate,UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,ZYCNoticePushViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollContentView;
@property (nonatomic, strong) UIView *bgContentView;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *comfirmButton;
@property (nonatomic, strong) UITextField *titleTextField;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) UITextView *contentTextView;
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) LxGridViewFlowLayout * layout;

@property (nonatomic, strong) UILabel *tipLabel;

@end
@implementation ZYCProtalNoticeView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.scrollContentView];
        [self addSubview:self.bgContentView];
        [self.bgContentView addSubview:self.cancelButton];
        [self.bgContentView addSubview:self.comfirmButton];
        [self.bgContentView addSubview:self.titleTextField];
        [self.bgContentView addSubview:self.line];
        [self.bgContentView addSubview:self.contentTextView];
        [self.bgContentView addSubview:self.collectionView];
        [self.bgContentView addSubview:self.pushRangeView];
        [self.bgContentView addSubview:self.tipLabel];
        [self setupContaints];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)
                  name:UITextFieldTextDidChangeNotification object:self.titleTextField];
    }
    return self;
}


#pragma mark UICollectionViewDelegate && UICollectionViewDataSource
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.selectedPhotos.count == BTImageTotalNumber) {
        return self.selectedPhotos.count;
    }else{
        return self.selectedPhotos.count + 1;
    }
}

-(__kindof UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([TZTestCell class]) forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    cell.gifLable.hidden = YES;
    
    if (indexPath.item == self.selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"x"];
        cell.deleteBtn.hidden = YES;
    }else {
        cell.imageView.image = self.selectedPhotos[indexPath.row];
        cell.asset = self.selectedAssets[indexPath.item];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

-(void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == self.selectedPhotos.count) {
        if ([self.delegate respondsToSelector:@selector(protalNoticeViewDidClickAddPhoto)]) {
            [self.delegate protalNoticeViewDidClickAddPhoto];
        }
    }else{
        [self browserPhotoIndexPath:indexPath];
    }
}

- (void)browserPhotoIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *browserDataArr = [NSMutableArray array];
    NSUInteger index = indexPath.item;
    [self.selectedAssets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YBIBImageData *data = [YBIBImageData new];
        data.imagePHAsset = obj;
        [browserDataArr addObject:data];
    }];
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = browserDataArr;
    browser.currentPage = index;
    [browser show];
}

#pragma mark - ZYCNoticePushViewDelegate
- (void)noticePushViewDidClick{
    if ([self.delegate respondsToSelector:@selector(protalNoticeViewDidClickPushRange)]) {
        [self.delegate protalNoticeViewDidClickPushRange];
    }
}


#pragma mark - UITextViewDelegate
-(void) textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length < 1) {
        textView.text = ZYCContentPlaceholder;
        textView.textColor = ZYCContentPlaceholderColor;
    }
}

-(void) textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:ZYCContentPlaceholder]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}



#pragma mark - Notification Method
-(void)textFieldEditChanged:(NSNotification *)noti{
    UITextField *textField = (UITextField *)noti.object;
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > MAX_STARWORDS_LENGTH)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}


#pragma mark - getters
- (UIScrollView *)scrollContentView {
    if (!_scrollContentView) {
        _scrollContentView = [[UIScrollView alloc] init];
    }
    return _scrollContentView;
}

- (UIView *)line {
    if (!_line) {
        _line = [[UIView alloc] init];
        _line.backgroundColor = HEX_RGB(@"#EAEAEA");
    }
    return _line;
}



- (UIView *)bgContentView {
    if (!_bgContentView) {
        _bgContentView = [[UIView alloc] init];
        _bgContentView.backgroundColor = [UIColor whiteColor];
    }
    return _bgContentView;
}


- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithTitle:@"取消" normalTitleColor:HEX_RGB(@"000000") selectTitleColor:HEX_RGB(@"000000") titleFont:kCustomFont(@"PingFangSC-Regular", 16.0f)];
        [_cancelButton addTarget:self action:@selector(clickCancelAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UIButton *)comfirmButton {
    if (!_comfirmButton) {
        _comfirmButton = [[UIButton alloc] init];
        [_comfirmButton setTitle:@"发布" forState:UIControlStateNormal];
        _comfirmButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 16.0f);
        [_comfirmButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _comfirmButton.backgroundColor = HEX_RGB(@"#009B4C");
        [_comfirmButton addTarget:self action:@selector(clickComfirmAction:) forControlEvents:UIControlEventTouchUpInside];
        _comfirmButton.layer.cornerRadius = 2.0f;
        _comfirmButton.layer.masksToBounds = YES;
    }
    return _comfirmButton;
}


- (UITextField *)titleTextField {
    if (!_titleTextField) {
        _titleTextField = [[UITextField alloc] init];
        _titleTextField.font = kSystemBoldFont(16.0f);
        _titleTextField.textAlignment = NSTextAlignmentLeft;
        _titleTextField.textColor = HEX_RGB(@"#313733");
        _titleTextField.delegate = self;
        _titleTextField.placeholder = @"请输入不超过40个字符的标题";
        _titleTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _titleTextField;
}

- (UITextView *)contentTextView {
    if (!_contentTextView) {
        _contentTextView = [[UITextView alloc] init];
        _contentTextView.delegate = self;
        _contentTextView.font = kCustomFont(@"PingFangSC-Regular", 16.0f);
        _contentTextView.text = ZYCContentPlaceholder;
        _contentTextView.textColor = ZYCContentPlaceholderColor;
    }
    return _contentTextView;
}

-(UICollectionView *) collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.contentInset = UIEdgeInsetsMake(10, 0, 10, 0);
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:NSStringFromClass([TZTestCell class])];
        
    }
    return _collectionView;
}

-(LxGridViewFlowLayout *) layout{
    if (!_layout) {
        _layout = [[LxGridViewFlowLayout alloc] init];
        _layout.itemSize = CGSizeMake(98.0, 98.0f);
        _layout.minimumLineSpacing = 0;//行间距
        _layout.minimumInteritemSpacing = 0;//列间距
        _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return _layout;
}

- (ZYCNoticePushView *)pushRangeView {
    if (!_pushRangeView) {
        _pushRangeView = [[ZYCNoticePushView alloc] init];
        _pushRangeView.delegate = self;
    }
    return _pushRangeView;
}


- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [UILabel LabelWithString:@"*添加附件的通知需要在PC端进行发布" Font:kCustomFont(@"PingFangSC-Regular", 13.0f) titleColor:HEX_RGB(@"#FF0000") textAlignment:ZZTextAlignmentLeft];
    }
    return _tipLabel;
}
#pragma mark - setters
-(void) setSelectedPhotos:(NSMutableArray *)selectedPhotos{
    _selectedPhotos = selectedPhotos;
    [self.collectionView reloadData];
}
#pragma mark - method Action
- (void)clickCancelAction:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(protalNoticeViewDidClickCancel)]) {
        [self.delegate protalNoticeViewDidClickCancel];
    }
}

- (void)clickComfirmAction:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(protalNoticeViewDidClickComfirm)]) {
        [self.delegate protalNoticeViewDidClickComfirm];
    }
}

-(void) deleteBtnClick:(UIButton *)sender{
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    [self.collectionView reloadData];
}

#pragma mark - LxGridViewDataSource

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < _selectedPhotos.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < _selectedPhotos.count && destinationIndexPath.item < _selectedPhotos.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    [_selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [_selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    
    id asset = _selectedAssets[sourceIndexPath.item];
    [_selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [_selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    
    [_collectionView reloadData];
}

#pragma mark - UI
- (void)setupContaints{
    [self.scrollContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    [self.bgContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollContentView);
    }];
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgContentView).offset(18.0f);
        make.top.equalTo(self.bgContentView).offset(42.0f);
        make.size.mas_equalTo(CGSizeMake(58.0f, 33.0f));
    }];
    
    [self.comfirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.bgContentView).offset(-18.0f);
        make.top.equalTo(self.bgContentView).offset(42.0f);
        make.size.mas_equalTo(CGSizeMake(58.0f, 33.0f));
    }];
    
    [self.titleTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgContentView).offset(33.0f);
        make.right.equalTo(self.bgContentView).offset(-33.0f);
        make.top.equalTo(self.cancelButton.mas_bottom).offset(55.0f);
    }];
    
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgContentView).offset(33.0f);
        make.right.equalTo(self.bgContentView).offset(-33.0f);
        make.top.equalTo(self.titleTextField.mas_bottom).offset(18.0f);
        make.height.mas_equalTo(1);
    }];
    
    [self.contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line.mas_bottom).offset(25.0f);
        make.left.equalTo(self.bgContentView).offset(33.0f);
        make.right.equalTo(self.bgContentView).offset(-33.0f);
        make.height.mas_equalTo(103.f);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentTextView.mas_bottom).offset(10.0f);
        make.left.equalTo(self.bgContentView).offset(33.0f);
        make.right.equalTo(self.bgContentView).offset(-33.0f);
        make.height.mas_equalTo(120.f);
    }];
    [self.pushRangeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgContentView).offset(33.0f);
        make.right.equalTo(self.bgContentView).offset(-33.0f);
        make.top.equalTo(self.collectionView.mas_bottom).offset(16.0f);
        make.height.mas_equalTo(55.0f);
    }];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgContentView).offset(33.0f);
        make.top.equalTo(self.pushRangeView.mas_bottom).offset(25.0f);
    }];
}

- (NSString *)title{
    return self.titleTextField.text;
}

- (NSString *)content{
    if ([self.contentTextView.text isEqualToString:ZYCContentPlaceholder]) {
        return nil;
    }
    return self.contentTextView.text;
}
@end
